import 'dart:math';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/mine/mine_xspace.dart' show XspaceVoiceView;
import 'package:find_friend/pages/xspace/model/artclemodel.dart';
import 'package:find_friend/pages/xspace/school/view/xcommbar.dart';
import 'package:find_friend/pages/xspace/school/view/xdiscuss_image.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'xcomment.dart';
import 'xdiscussdetail_cell.dart';

class XDiscussDetailPage extends StatefulWidget {

  final ReplyModel model;
  final String aid; // 文章id;
  final Function onRefreshDetail;

  XDiscussDetailPage({Key key, this.model, this.aid, this.onRefreshDetail}) : super(key: key);

  @override
  _XDiscussDetailPageState createState() => _XDiscussDetailPageState();
}

class _XDiscussDetailPageState extends State<XDiscussDetailPage> {
  
  final FocusNode _focusNode = FocusNode();
  List<ReplyModel> list = [];
  RefreshController _refreshController = RefreshController(initialRefresh: true);

  int replys = 0;
  int upvotes = 0;
  int page = 0;
  bool ishot = true;
  bool isrefreshDetail = false;
  XCommentWidget _commentWidget;
  @override
  void initState() {
    super.initState();

    _requestDetail();

    _commentWidget = XCommentWidget(
                articleId: widget.aid,
                focusNode: _focusNode,           // 焦点
                onRefreshData: _onCommentRefresh, // 刷新数据
                rid: widget.model.id.toString(),
              );
  }

  _clear() {
    if(_focusNode != null) _focusNode.unfocus();
  }

  _onCommentRefresh(bool isreload){
    _clear();
    isrefreshDetail = true;
    if(isreload) _refreshController.requestRefresh();
  }
  
  

  _onRefresh() {
    page = 1;
    _requestDetail(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _requestDetail();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 5) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _requestDetail({isrefresh = false}) {
    Networktool.request(API.articlereply+ "/" + widget.model.id.toString(), params: {"rows":10, "page":page, "upvote_order": ishot}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        List arr = data["data"]["reply"] ?? [];
        _endNormoreData(arr.length);
        if(isrefresh) list.clear();
        arr.forEach((element) { 
          list.add(ReplyModel.fromJson(element));
        });

        upvotes = data["data"]["upvotes"] ?? 0;
        replys = data["data"]["replys"] ?? 0;
        widget.model.upvotes = upvotes;
        widget.model.replys = replys;
        setState(() {
          
        });
      }
    }
    ,finaly: () => _endrefres());
  }

  

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    final padding = MediaQuery.of(context).padding;
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomPadding: false,
      // appBar: AppBar(
      //   backgroundColor: Colors.white,
      //   centerTitle: true,
      //   title: Text("评论详情"),
      //   actions: [
      //     IconButton(
      //       onPressed: (){
      //          AlertTool.showBottomShareDialog(context, replyModel: widget.model, onRefreshData: (){
      //           if(widget.onRefreshDetail != null) widget.onRefreshDetail();
      //            Navigator.pop(context);
      //          });
      //       },
      //       icon: Icon(Icons.more_horiz),
      //     )
      //   ],
      //   leading: IconButton(
      //     onPressed: (){
      //       if(widget.onRefreshDetail != null) widget.onRefreshDetail();
      //       Navigator.of(context).pop();
      //     },
      //     icon: Image.asset("assets/fanhui.png"),
      //   ),
      // ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          _commentWidget.clear();
        },
        child: SafeArea(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: AppBar(
                  backgroundColor: Colors.white,
                  centerTitle: true,
                  title: Text("评论详情"),
                  actions: [
                    IconButton(
                      onPressed: (){
                        AlertTool.showBottomShareDialog(context, replyModel: widget.model, onRefreshData: (){
                          if(widget.onRefreshDetail != null) widget.onRefreshDetail();
                          Navigator.pop(context);
                        });
                      },
                      icon: Icon(Icons.more_horiz),
                    )
                  ],
                  leading: IconButton(
                    onPressed: (){
                      if(widget.onRefreshDetail != null) widget.onRefreshDetail();
                      Navigator.of(context).pop();
                    },
                    icon: Image.asset("assets/fanhui.png"),
                  ),
                ),
              ),
              Expanded(
                child: Stack(
                  children: [
                    CustomRefreshWidget(
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      controller: _refreshController,
                      child: ListView.builder(
                          itemCount: list.length + 1,
                          padding: const EdgeInsets.only(bottom: 50),
                          itemBuilder: (context, index){
                            if(index == 0) {
                              return Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(top: 10, left: 20.5),
                                    child: Row(
                                      children: [
                                        InkWell(
                                          onTap: (){
                                            Navigator.of(context).pushNamed("/minepreview", arguments: widget.model.mobile);
                                          },
                                          child: CustomCircleAvatar(url: widget.model.avatar, size: 46,)
                                        ),
                                        SizedBox(width: 8,),
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Text(widget.model.username, style: instanceTextStyle(13, APP_font_black),),
                                              Padding(
                                                padding: const EdgeInsets.only(right: 50),
                                                child: Text("个性签名：${widget.model.bio ?? ''}", maxLines: 1, overflow: TextOverflow.ellipsis, style: instanceTextStyle(9, APP_font_grey),),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 9.5,),
                                  // 文本消息
                                  Offstage(
                                    offstage: widget.model.content == null,
                                    child: Padding(
                                      padding: const EdgeInsets.only(left:21.0, bottom: 9.5,),
                                      child: Text(widget.model.content ?? "", style: instanceTextStyle(12, APP_font_black),),
                                    ),
                                  ),
                                  
                                  // 照片
                                  Offstage(
                                    offstage: widget.model.photo == null,
                                    child: Padding(
                                      padding: const EdgeInsets.only(left: 21),
                                      child: XDiscussImagesWidget(list: widget.model.photo ?? [], height: 76,)
                                    ),
                                  ),

                                  // 语音
                                  Offstage(
                                    offstage: widget.model?.voice == null,
                                    child: Padding(
                                      padding: const EdgeInsets.only(left:21, top: 10),
                                      child: XspaceVoiceView(width: size.width * 0.45, voice: widget.model?.voice,),
                                    ),
                                  ),
                                  // comment
                                  XpageCommentWidget(
                                    replyModel: widget.model, 
                                    onRefreshData: (){
                                      if(widget.onRefreshDetail != null) widget.onRefreshDetail();
                                      Navigator.pop(context);
                                    },
                                    onTapComment: () => _focusNode.requestFocus(),
                                  ),
                                  
                                  // 回复
                                  InkWell(
                                    onTap: (){
                                      setState(() {
                                        ishot = !ishot;
                                        _refreshController.requestRefresh();
                                      });
                                    },
                                    child: Container(
                                        color: APP_scaffold_back_color,
                                        padding: const EdgeInsets.only(top: 10, bottom: 10),
                                        child: Container(
                                          padding: const EdgeInsets.symmetric(horizontal: 20.5),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text("回复", style: instanceTextStyle(14, APP_font_black),),
                                              Row(children: [
                                                Text(ishot ? "热":"新", style: instanceTextStyle(11, ishot ? APP_verify_error_color : const Color(0xff00CEE6))),
                                                SizedBox(width: 2.5,),
                                                Image.asset("assets/re.png", color: ishot ? APP_verify_error_color : const Color(0xff00CEE6),)
                                              ],),
                                            ],
                                          ),
                                        ),
                                      ),
                                  ),

                                  Offstage(
                                    offstage: list.length != 0,
                                    child: Container(
                                      width: size.width,
                                      padding: const EdgeInsets.symmetric(vertical: 15),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Image.asset("assets/que2.png"),
                                          SizedBox(height: 5,),
                                          Text("别走~此处需要你的评论", style: TextStyle(fontFamily: "cute", fontSize: 15, color: Colors.black),),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              );
                            } else {
                              return GestureDetector(
                                onTap: (){
                                  // AlertTool.showToast("回复");
                                  _commentWidget.requestFocusReply(list[index - 1].mobile, list[index - 1].username, widget.model.id.toString());
                                },
                                onLongPress: (){
                                  AlertTool.showBottomShareDialog(context, replyModel: list[index - 1], onRefreshData: (){
                                    setState(() {
                                      list.removeAt(index - 1);
                                    });
                                  });
                                },
                                child: Container(
                                  color: APP_scaffold_back_color,
                                  child: XdetailDiscussCell2(model: list[index - 1], onRefreshData: (){
                                    _refreshController.requestRefresh();
                                  },)
                                )
                              );
                            }
                          }
                        ),
                    ),
                    Positioned(
                      bottom: 0,
                      child: _commentWidget,
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      )
      );
  }
}

